<?php

class Ecard_EcardController extends Core_Controller_Action_Standard
{
  public function indexAction()
  {
    $this->view->someVar = 'someVal';
  }
  
  public function createAction()
  {
	if( !$this->_helper->requireUser()->isValid() ) {
		return;
	}
    
    $this->view->form = $form = new Ecard_Form_Create();
    
    $imageTable = Engine_Api::_()->getItemTable('ecard_image');    
    $select = $imageTable->select()
                    ->where('approve = ?',1);
    $images = $imageTable->fetchAll($select);                             
    $this->view->images = $images;   
    
    $fontTable = Engine_Api::_()->getItemTable('ecard_font');    
    $select = $fontTable->select()
                        ->where('approve = ?',1);
    $fonts = $fontTable->fetchAll($select);
                                   
    $this->view->fonts = $fonts;     

	$this->view->error = '';
	$this->view->redir_url = $redir_url = '';
	$this->view->upload_path = $upload_path = APPLICATION_PATH . '/public/ecard/user_imgs/';

   $form->text_color->setValue(Engine_Api::_()->getApi('settings','core')->getSetting('ecard.text_color','#101010'));
   
   $b = Engine_Api::_()->getApi('settings','core')->getSetting('ecard.text_color','#101010');
   $this->view->b = $b;    
   
    // Check post
    if( !$this->getRequest()->isPost() ) {
    
       return;
    }    

    // Check form validate
    if(!$form->isValid($this->getRequest()->getPost())){
        return;
    }
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

    $values = $this->_getAllparams();

	$text_alignment = 0;
	switch($values['text_alignment']){
		case 'top' : 
			$text_alignment = 0;
			break;
		case 'mid' : 
			$text_alignment = 1;
			break;
		case 'bot' : 
			$text_alignment = 2;
			break;
		default : 
			$text_alignment = 0;
			break;
	}

	$text = html_entity_decode($values['text_content']) ;
	
	if(empty($text)){
		$this->view->error = 'Error: Text not properly formatted.' ;
		return;
	}
	
	// customizable variables
	$font_file 		= APPLICATION_PATH . '/application/modules/Ecard/externals/images/font_source/'.$values['font_title'].'.ttf';
	$font_size  	= $values['text_size'] ; // font size in pts
	$font_rgb     =  $this->hex_to_rgb($values['text_color']);
//	$font_color 	= ($values['text_color']?'#'.$values['text_color']:'#ffffff');
    
    // check file by user or system
//	if(isset($values['file_by_user']) && $values['file_by_user']){
//		$image_file 	= $upload_path.$values['background_name'];
//	}else{
//		$image_file 	= APPLICATION_PATH . '/public/tagsmaker/imgs/bg_'.$values['background_name'].'0.jpg';
//	}
    
    $image_item = Engine_Api::_()->getItem('ecard_image',$values['background_id']);
    
    $photo_url = $image_item->getPhotoUrl();
    
//    $path = APPLICATION_PATH.'/'. $photo_url;
    
//    print_r($path);die;
     
	//$image_file = 'D:\wamp\www\Custom\testAlbum/public/tagsmaker/imgs/bg_00110.jpg';	
    $image_file = APPLICATION_PATH.'/'. $photo_url;
	// trust me for now...in PNG out PNG
	$mime_type 			= 'image/jpeg' ;
	$extension 			= '.jpg' ;
	$s_end_buffer_size 	= 4096 ;

	// check for GD support
	if(!function_exists('ImageCreate')){
		$this->view->error = 'Error: Server does not support PHP image generation';
		return;
	}
	
	// create and measure the text
	$box = @ImageTTFBBox($font_size,0,$font_file,$text) ;
	
//    print_r($font_file);die;
   
	$text_width = abs($box[2]-$box[0]);
	$text_height = abs($box[5]-$box[3]);
    
	$image =  imagecreatefromjpeg($image_file);
	
	if(!$image || !$box)
	{
		$this->view->error = 'Error: The server could not create this image.';
		return;
	}
	
	// allocate colors and measure final text position
	$font_color = ImageColorAllocate($image,$font_rgb['red'],$font_rgb['green'],$font_rgb['blue']) ;
    
	$image_width = imagesx($image);
	$image_height = imagesy($image);
	// x and y for the bottom right of the text
	// so it expands like right aligned text
	$x_finalpos 	= floor(($image_width-$text_width)/2)+$text_width;
	if($text_alignment == 2){
		$y_finalpos 	= $image_height - ($text_height);
	}else{
		//$y_finalpos 	= ($text_height + 5) + $text_alignment * floor($image_height/3);
		$y_finalpos 	=  5 + $text_alignment * floor($image_height/3) - $box[5];
	}
	
	$put_text_x = $image_width - $text_width - ($image_width - $x_finalpos);
	$put_text_y = $y_finalpos;
	
	//multiline
	$text = str_replace ("\r", '', $text); //Remove windows line-breaks
	$srcLines = split ("\\n", $text); //Split text into "lines"
	$dstLines = Array(); // The destination lines array.
	foreach ($srcLines as $currentL) {
		$line = '';
		$words = split (" ", $currentL); //Split line into words.
		foreach ($words as $word) {
			$dimensions = imagettfbbox($font_size, 0, $font_file, $line.' '.$word);
			$lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line, if the word is to be included
			if ($lineWidth > $image_width && !empty($line) ) { // check if it is too big if the word was added, if so, then move on.
				$dstLines[] = trim($line); //Add the line like it was without spaces.
				$line = '';
			}
			$line .= $word.' ';
		}
		$dstLines[] =  trim($line); //Add the line when the line ends.
	}
	//Calculate lineheight by common characters.
	$dimensions = imagettfbbox($font_size, 0, $font_file, "MXQJPmxqjp123"); //use a custom string to get a fixed height.
	$lineHeight = $dimensions[1] - $dimensions[5]; // get the heightof this line

    $align = '';
	$align = strtolower(substr($align,0,1)); //Takes the first letter and converts to lower string. Support for Left, left and l etc.
	if($text_alignment == 2){
		$y_finalpos 	= $image_height - $lineHeight*count($dstLines) - $box[5] - 5;
	}elseif($text_alignment == 1){
		$y_finalpos 	=  floor($image_height/2) - floor($lineHeight*count($dstLines)/2) - $box[5] - 5;
	}else{
		$y_finalpos 	=  5 + $text_alignment * floor($image_height/3) - $box[5];
	}
	foreach ($dstLines as $nr => $line) {
		if ($align != "l") {
			$dimensions = imagettfbbox($font_size, 0, $font_file, $line);
			$lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line
			$x = '';
            if ($align == "r") { //If the align is Right
				$locX = $x + $image_width - $lineWidth;
			} else { //If the align is Center
				$locX = $x + ($image_width/2) - ($lineWidth/2);
			}
		} else { //if the align is Left
			$locX = $x;
		}
		if($text_alignment == 2){
			$locY = $y_finalpos + ($nr * $lineHeight);
		}else{
			$locY = $y_finalpos + ($nr * $lineHeight);
		}
		//Print the line.
//        print_r($image);
//        echo '<br>';
//        print_r($font_size);
//        echo '<br>';
//        print_r($locX);
//        echo '<br>';
//        print_r($locY);
//        echo '<br>';
//        print_r($font_color);
//        echo '<br>';
//        print_r($font_file);
//        echo '<br>';
//        print_r($line);
//        echo '<br>';        

		imagettftext($image, $font_size, 0, $locX, $locY, $font_color, $font_file, $line);
	}        
	//multiline
 //   die;	
	
	//delete this
	//header('Content-type: ' . $mime_type) ;
	//ImagePNG($image) ;
	//ImageDestroy($image) ;
	//exit ;
	//delete this
	
	
	$ecardTable = Engine_Api::_()->getDbtable('ecards', 'ecard');
	
    $values = array_merge($values,array(
		'owner_id' => $viewer->getIdentity(),
		'image_id' => $values['background_id'],
    ));

    //save form values
    $db = $ecardTable->getAdapter();
    $db->beginTransaction();
    try
    {            
    	$ecard = $ecardTable->createRow();
    	$ecard->setFromArray($values);
        $ecard->save();

    	$save_path = $upload_path.time().'_'.$viewer->getIdentity().'.jpg';
    
    
    	//print_r($save_path);die;
        
        
    	ImageJPEG($image, $save_path) ;
    	ImageDestroy($image) ;
    	
    	$ecard->setPhoto($save_path);
    	$ecard->save();
        
        $db->commit();   
      
        $form->addNotice($this->view->translate('Your talktangle created successfully.'));                  
        
    }
    catch(Exception $e)
    {
        $db->rollBack();
        throw $e;
    }          


//	$imageTable = Engine_Api::_()->getDbtable('photos', 'album');
//	$image = $imageTable->createRow();
//	$photo->setFromArray(array(
//	  'owner_type' => 'user',
//	  'owner_id' => $viewer->getIdentity()
//	));
//	$photo->save();
//	$photo->setPhoto($save_path);
//	
//	$photo->collection_id = $ecard_album->album_id;
//	$photo->save();
//
//	if( !$ecard_album->photo_id )
//	{
//	  $ecard_album->photo_id = $photo->getIdentity();
//	  $ecard_album->save();
//	}
//	
//	unlink($save_path);
//	$this->view->redir_url = $redir_url = $photo->getHref().'/backlink/1';
//	return;
    
  } 
    
    
  function hex_to_rgb($hex) {
		// remove '#'
		if(substr($hex,0,1) == '#')
			$hex = substr($hex,1) ;

		// expand short form ('fff') color to long form ('ffffff')
		if(strlen($hex) == 3) {
			$hex = substr($hex,0,1) . substr($hex,0,1) .
				   substr($hex,1,1) . substr($hex,1,1) .
				   substr($hex,2,1) . substr($hex,2,1) ;
		}
	
		if(strlen($hex) != 6){
			$this->view->error = 'Error: Invalid color "'.$hex.'"';
			return;
		}
	
		// convert from hexidecimal number systems
		$rgb['red'] = hexdec(substr($hex,0,2)) ;
		$rgb['green'] = hexdec(substr($hex,2,2)) ;
		$rgb['blue'] = hexdec(substr($hex,4,2)) ;
	
		return $rgb ;
	} 
}
